package com.wh.wisdomsite.xbox.server.controller.ba;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.ba.entity.CommonDict;
import com.wh.wisdomsite.xbox.ba.service.ICommonDictService;
import com.wh.wisdomsite.xbox.common.util.ResManager;
import com.wh.wisdomsite.xbox.pojo.ba.CommonDictIn;
import com.wh.wisdomsite.xbox.server.manager.UserMapManager;
import com.wh.wisdomsite.xbox.server.util.UserUtils;
import com.wh.wisdomsite.xbox.utils.StringUtils;
import com.wh.wisdomsite.xbox.utils.date.DateTool;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil;
import com.wh.wisdomsite.xbox.utils.json.JsonUtil_Org;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/***
 *字典配置控制器Controller
 * @author 杨世强
 * @date 16:40 2018/8/2
 * @Copyright 公司版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2016
 * @version V1.0
 */
@Controller
@RequestMapping(value = "/commonDict")
public class CommonDictController {

    private static final Log logger = LogFactory.getLog(CommonDictController.class);
    @Autowired
    private ICommonDictService iCommonDiceService;

    /**
     * 跳转到字典配置页面
     *
     * @return
     */
    @RequiresPermissions("rules:ba_commonDict_page")
    @RequestMapping(value = "/index.do", method = RequestMethod.GET)
    public String index() {
        return "ba/commonDict/commonDictList";
    }

    /**
     * 获取字典列表
     *
     * @param response
     * @param in
     */
    @RequiresPermissions("rules:ba_commonDict_find")
    @RequestMapping(value = "/commonDictList.do")
    public void CommonDictList(HttpServletResponse response, CommonDictIn in) {
        try {
            logger.info("加载数据字典配置列表-->>开始");
            logger.info("加载数据字典配置列表-->>开始-->>" + in.getPage());
            if (in.getPage() == 0) in.setPage(1);
            if (in.getRows() == 0) in.setRows(10);
            Page<CommonDict> page = new Page<>();
            page.setCurrent(in.getPage());
            page.setSize(in.getRows());
            //设置条件
            EntityWrapper<CommonDict> ewCommonDict = new EntityWrapper<CommonDict>();
            ewCommonDict.setEntity(new CommonDict());
            if (StringUtils.isNotEmpty(in.getModelCode())) {
                ewCommonDict.eq("modelCode", in.getModelCode());
            }
            if (StringUtils.isNotEmpty(in.getFunCode())) {
                ewCommonDict.eq("funCode", in.getFunCode());
            }
            if (StringUtils.isNotEmpty(in.getPropertyCode())) {
                ewCommonDict.eq("propertyCode", in.getPropertyCode());
            }
            ewCommonDict.orderBy("modelCode,funCode,propertyCode,createDate", true);
            Page<CommonDict> commonDictPage = iCommonDiceService.selectPage(page, ewCommonDict);
            JSONObject json = new JSONObject();
            JSONArray array = new JSONArray();
            if (commonDictPage.getRecords().size() > 0) {
                for (CommonDict commonDict : commonDictPage.getRecords()) {
                    JSONObject object = new JSONObject(commonDict);
                    object.put("cdId", commonDict.getCdId());
                    object.put("createDate", DateTool.format(commonDict.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
                    array.put(object);
                }
            }
            json.put("total", commonDictPage.getTotal());
            json.put("rows", array);
            ResManager.getJsonOut(response).print(json);
            logger.info("加载数据字典配置列表-->>结束");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 字典详情
     *
     * @param commonDictIn
     * @param request
     * @return
     */
    @RequiresPermissions("rules:us_office_view")
    @RequestMapping("commonDictDesc.do")
    public String commonDictDetails(CommonDictIn commonDictIn, HttpServletRequest request) {
        logger.info("字典详情-->>开始");
        CommonDict commonDict = iCommonDiceService.selectById(commonDictIn.getCdId());
        if(null != commonDict.getCreateBy()){
            commonDict.setCreateBy(UserMapManager.getUserLoginNameInMap(commonDict.getCreateBy()));
        }
        request.setAttribute("commonDict", commonDict);
        request.setAttribute("createDate", DateTool.format(commonDict.getCreateDate(), "yyyy-MM-dd HH:mm:ss"));
        logger.info("字典详情-->>结束");
        return "ba/commonDict/commonDictDesc";
    }

    /**
     * 删除字典
     *
     * @param commonDict
     * @param response
     */
    @RequiresPermissions("rules:ba_commonDict_del")
    @RequestMapping(value = "del.do", method = RequestMethod.GET)
    public void del(CommonDict commonDict, HttpServletResponse response) {
        try {
            logger.info("删除字典-->>开始");
            iCommonDiceService.deleteById(commonDict.getCdId());
            logger.info("删除字典-->>结束");
            ResManager.getJsonOut(response).print(JsonUtil_Org.returnTrue("删除成功"));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("删除字典-->>Exception" + e.getMessage());
        }
    }

    /**
     * 更新或修改字典
     *
     * @param commonDict
     * @param response
     */
    @RequiresPermissions("rules:ba_commonDict_edit")
    @RequestMapping(value = "/save.do", method = RequestMethod.POST)
    public void save(CommonDict commonDict,HttpServletResponse response) {
        //查看字典是否已经存在
        try {
            if (StringUtils.isNotEmpty(commonDict.getCdId())) {
                logger.info("修改字典-->>开始");
                iCommonDiceService.updateById(commonDict);
                System.out.println("完毕");
                logger.info("修改字典-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("更新字典成功"));
            } else {
                logger.info("添加字典-->>开始");
                commonDict.setCreateBy(UserUtils.getCurrentUser().getUsId());
                commonDict.setCreateDate(new Date());
                iCommonDiceService.insert(commonDict);
                logger.info("添加字典-->>结束");
                response.getWriter().write(JsonUtil_Org.returnTrue("添加字典成功"));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("添加字典-->>Exception" + e.getMessage());
        }
    }

    /**
     * 获取所有功能模块
     *
     * @param response
     */
    @RequestMapping(value = "/getModelList.do")
    public void getModelList(HttpServletResponse response) {
        List<CommonDict> commonDicts = null;
        try {
            logger.info("获取所有模块-->>开始");
            EntityWrapper<CommonDict> ewCommonDict = new EntityWrapper<CommonDict>();
            ewCommonDict.setEntity(new CommonDict());
            ewCommonDict.groupBy("modelName");
            commonDicts = iCommonDiceService.selectList(ewCommonDict);
        } catch (Exception e) {
            e.printStackTrace();
            commonDicts = new ArrayList<>();
            logger.error("获取所有模块-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonDicts));
        logger.info("获取所有模块-->>结束");
    }


    /**
     * 根据模块代码获取所有功能
     *
     * @param response
     */
    @RequestMapping(value = "/getFunList.do")
    public void getFunList(HttpServletResponse response, String modelCode) {
        List<CommonDict> commonDicts = null;
        try {
            logger.info("获取所有功能模块-->>开始");
            EntityWrapper<CommonDict> ewCommonDict = new EntityWrapper<CommonDict>();
            ewCommonDict.setEntity(new CommonDict());
            ewCommonDict.eq("modelCode", modelCode);
            ewCommonDict.groupBy("funCode");
            commonDicts = iCommonDiceService.selectList(ewCommonDict);
        } catch (Exception e) {
            e.printStackTrace();
            commonDicts = new ArrayList<>();
            logger.error("获取所有功能模块-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonDicts));
        logger.info("获取所有功能模块-->>结束");
    }

    /**
     * 根据功能代码获取所有属性
     *
     * @param response
     */
    @RequestMapping(value = "/getPropertyList.do")
    public void getPropertyList(HttpServletResponse response, String funCode) {
        List<CommonDict> commonDicts = null;
        try {
            logger.info("获取所有属性-->>开始");
            EntityWrapper<CommonDict> ewCommonDict = new EntityWrapper<CommonDict>();
            ewCommonDict.setEntity(new CommonDict());
            ewCommonDict.eq("funCode", funCode);
            ewCommonDict.groupBy("propertyCode");
            commonDicts = iCommonDiceService.selectList(ewCommonDict);
        } catch (Exception e) {
            e.printStackTrace();
            commonDicts = new ArrayList<>();
            logger.error("获取所有属性-->>异常Exception " + e.getMessage());
        }
        ResManager.getJsonOut(response).print(JsonUtil.Json2All(commonDicts));
        logger.info("获取所有属性-->>结束");
    }

    /**
     * 从公共字典中获取下拉框选项
     *
     * @param response
     * @param in
     * @author 丁奕
     */
    @RequestMapping(value = "/getCommonDictOptions", method = RequestMethod.GET)
    public void getCommonDictOptions(HttpServletResponse response, CommonDictIn in) {
        //设置条件
        logger.info("加载公共字典，获取下拉框选项-->>开始");
        EntityWrapper<CommonDict> ewCommonDict = new EntityWrapper<>();
        ewCommonDict.setEntity(new CommonDict());
        if (StringUtils.isNotEmpty(in.getModelCode())) {
            ewCommonDict.eq("modelCode", in.getModelCode());
        }
        if (StringUtils.isNotEmpty(in.getFunCode())) {
            ewCommonDict.eq("funCode", in.getFunCode());
        }
        if (StringUtils.isNotEmpty(in.getPropertyParentCode())) {
            ewCommonDict.eq("propertyParentCode", in.getPropertyParentCode());
        }else{
            ewCommonDict.eq("propertyParentCode", "0");
        }
        ewCommonDict.orderBy("propertySort", true);
        //根据条件查询出所有的公共字典，为下拉选框提供数据
        List<CommonDict> commonDictList = iCommonDiceService.selectList(ewCommonDict);
        JSONArray array = new JSONArray();
        if (commonDictList.size() > 0) {
            for (CommonDict commonDict : commonDictList) {
                JSONObject object = new JSONObject(commonDict);
                array.put(object);
            }
        }
        ResManager.getJsonOut(response).print(array);
        logger.info("加载公共字典，获取下拉框选项-->>结束");
    }

    /**
     * 跳转至添加页面
     *
     * @return
     */
    @RequestMapping("/toCommonDict")
    public ModelAndView toAddCommonDict(String cdId, HttpServletRequest request) {
        logger.info("添加修改字典跳转-->>开始");
        if (StringUtils.isNotEmpty(cdId)) {
            CommonDict commonDict = iCommonDiceService.selectById(cdId);
            request.setAttribute("commonDict", commonDict);
            logger.info("添加修改字典跳转-->>开始");
        }
        return new ModelAndView("ba/commonDict/commonDictOption");
    }


}
